package cycling.taxi.com.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.Random;

import cycling.taxi.com.IConstants;
import cycling.taxi.com.R;
import cycling.taxi.com.person.ExitApplication;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.MD5Util;
import cycling.taxi.com.utils.PhoneUtils;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;
import cycling.taxi.com.zxing.android.CaptureActivity;

public class Tancfer extends AppCompatActivity implements View.OnClickListener,RequestCallback {
    private EditText holdname,holdphone,holdpass,assname,assphone,assval,fac;
    private Button btn,validate;
    private ImageView back;
    private TextView mTitleText;
    private RequestQueue queue;
    private String rad="()*";
    private Button mForward;
    private TextView mFilterText;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private static final int REQUEST_CODE_SCAN = 0x0000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_tancfer);
        initUi();
        back=(ImageView)findViewById(R.id.back);
        back.setOnClickListener(this);
        btn.setOnClickListener(this);
        validate.setOnClickListener(this);
        mForward.setOnClickListener(this);
        queue= Volley.newRequestQueue(this);
    }
    private void initUi(){
        mTitleText=(TextView)findViewById(R.id.title_text);
        back=(ImageView)findViewById(R.id.back);
        holdname=(EditText)findViewById(R.id.holdname);
        holdphone=(EditText)findViewById(R.id.holdmobile);
        holdpass=(EditText)findViewById(R.id.ed_password);
        assname=(EditText)findViewById(R.id.ed_assname);
        assphone=(EditText)findViewById(R.id.assmobile);
        assval=(EditText)findViewById(R.id.assval);
        fac=(EditText)findViewById(R.id.fac);
        btn=(Button)findViewById(R.id.repair_btn);
        validate=(Button)findViewById(R.id.validate);
        mTitleText.setText("发起过户");
        mFilterText=(TextView) findViewById(R.id.filter_text);
        mForward=(Button) findViewById(R.id.forward);
        mForward.setVisibility(View.VISIBLE);
        mForward.setBackground(getResources().getDrawable(R.drawable.pic_qrcode));
        mFilterText.setVisibility(View.VISIBLE);
        mFilterText.setText("扫一扫");
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.repair_btn:
                register();
                break;
            case R.id.validate:
                reqIdentifyCode();
                break;
            case R.id.forward:
                //扫一扫
                Intent intent = new Intent(Tancfer.this,CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                break;
        }

    }
    private String getHoldName() {
        return holdname.getText().toString().trim();
    }
    private String getHoldphone() {
        return holdphone.getText().toString().trim();
    }
    private String getHoldPass() {
        return holdpass.getText().toString().trim();
    }
    private String getAssName() {
        return assname.getText().toString().trim();
    }
    private String getAssPhone() {
        return assphone.getText().toString().trim();
    }
    private String getAssVal() {
        return assval.getText().toString().trim();
    }
    private String getFac() {
        return fac.getText().toString().trim();
    }

    @Override
    public void requestSuccess(RequestBean bean, Config config) {
        LogUtil.d("requestSuccess");
        if (bean.getStatusCode()==1){
            ToastUtil.getInstance().toast("过户成功");
            return;
        }
    }

    @Override
    public void requestFail(RequestBean bean, Config config) {
        LogUtil.d("requestFail");
        ToastUtil.getInstance().toast("过户失败");
    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {
        LogUtil.d("requestFail");
    }
    private void register() {
        if (!PhoneUtils.isMobileNO(getHoldphone())) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }
        if (!PhoneUtils.isMobileNO(getAssPhone())) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }
        if (TextUtils.isEmpty(getHoldName())){
            ToastUtil.getInstance().toast("请输入持有人姓名");
            return;
        }
        if (TextUtils.isEmpty(getHoldphone())){
            ToastUtil.getInstance().toast("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(getHoldPass())){
            ToastUtil.getInstance().toast("请输入密码");return;
        }
        if (TextUtils.isEmpty(getHoldName())){
            ToastUtil.getInstance().toast("请输入受让人姓名");
            return;
        }
        if (TextUtils.isEmpty(getAssPhone())){
            ToastUtil.getInstance().toast("请输入手机号");
            return;
        }
        if(TextUtils.isEmpty(getFac())){
            ToastUtil.getInstance().toast("请输入设备号");
            return;
        }
        if (TextUtils.isEmpty(getAssVal())||getAssVal().length()<4||!getAssVal().equals(rad)){
            ToastUtil.getInstance().toast("验证码不正确");return;
        }
            RequestParams params = new RequestParams.Builder()
                    .putParam("HoldName", getHoldName())
                    .putParam("HoldPhone", getHoldphone())
                    .putParam("HoldPass", MD5Util.MD5Encode(getHoldPass()))
                    .putParam("AssName", getAssName())
                    .putParam("AssPhone", getAssPhone())
                    .putParam("Fac", getFac())
                    .putParam("beanJson", SPUtil.getInstance().getData("beanJson"))
                    .build();
            //开始请求发送数据到服务器服务器
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String url = Urls.getGuoHu();//回去api路径

            RequestUtil.requestData(requestQueue,
                    IConstants.REGISTER,
                    url,
                    RM.GET,
                    RequestBean.class,
                    params,
                    this);

    }
    private void reqIdentifyCode() {
        String phone = getAssPhone();
        if (!PhoneUtils.isMobileNO(phone)) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }
//        String noncestr = "" + System.currentTimeMillis(); //时间戳
//        String sign = IdentifyUtils.getClientSign(phone, noncestr); //签名
        rad = RandomCode();
        //TODO  下面需要进行网络请求
        volleyGet();
        //请求成功的话加上以下代码
        startColdTime();

    }
    public void volleyGet(){
        // String path= "http://172.16.2.183:8080/CyclingBgTV1/appRepairByself/r.dop?content="+rad;
       // String path= Urls.getTest()+"?content="+rad;
        String mobile=getAssPhone();
        String path =Urls.getValidate()+mobile+Urls.getValidateContent()+rad+Urls.getValidateElse();
      //  String path="https://dx.ipyy.net/smsJson.aspx?action=send&userid=&account=AG00031&password=AG00031523&mobile="+mobile+"&content=您的验证码："+rad+"【塔西】&sendTime=&extno=";
        // String path = Urls.getRepair();18677365372
        StringRequest request = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                LogUtil.e(s);
                ToastUtil.getInstance().toast(s);
            }
        },null);
        queue.add(request);
    }
    private int timeC = 0;
    private void startColdTime() {
        timeC = 60;
        coldTimeing();
    }

    private void coldTimeing() {
        if (validate == null)
            return;
        setColdTime(timeC);
        if (timeC > 0) {
            validate.postDelayed(new Runnable() {
                @Override
                public void run() {
                    timeC--;
                    coldTimeing();
                }
            }, 1000);
        }
    }

    /**
     * @param num 倒计时时间, 如果小于等于0, 显示重新发送
     */
    private void setColdTime(int num) {
        if (validate == null) {
            return;
        }
        validate.setEnabled(num <= 0);
        if (num > 0) {
            validate.setText(num + "s");
        } else {
            validate.setText(R.string.str_register_resend);
        }
    }
    private String RandomCode(){
        String str="0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                fac.setText(content);
            }
        }
    }

}
